package hello.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.util.Date;

/**
 * @Author hiberk
 * @Date 2017/7/31 9:13
 */
@Controller
public class HelloController {

    @Resource
    SessionRegistry sessionRegistry;
    @Resource
    DataSource dataSource;

    @RequestMapping(value = "/welcome/**", method = RequestMethod.GET)
    @ResponseBody
    public String hello() throws Exception{
        return "hello, this is a security guide !!!!";
    }


    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    @ResponseBody
    public String admin() throws Exception{
//        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return "hello, this is a security guide---admin name  ";
    }

    @RequestMapping(value = {"/index/**", "/"}, method = RequestMethod.GET)
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String index(HttpServletRequest request, String message, String input, HttpServletResponse response) throws Exception{
        System.out.println("this route mapping" + "\t" + message + "---" + input);
        return "index";
    }
    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String form(Date hdate, String name, String[] ids) throws Exception{
        System.out.println("DateTimeFormat conversion!" + name + "\t" + hdate );
        return "index";
    }

    @RequestMapping(value = "/message", method = RequestMethod.GET)
    public String message() throws Exception{
        return "message";
    }

    @RequestMapping(value = "/indexLogin", method = RequestMethod.GET)
    public String login(@RequestParam(value = "error", required = false) String error, Model model) throws Exception{
        model.addAttribute("error", error);
        return "/login";
    }

    /*@InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }*/

}
